import React from 'react';
import { Icon, Button, message, Popover, Tooltip, Modal } from 'antd';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaLocaleProvider, WeaQrcode, WeaDialog, WeaTableEditable, WeaInput } from 'ecCom';
import CopyToClipboard from 'react-copy-to-clipboard';
import AddFieldVal from './AddFieldVal';
import { comsType } from '../../../../constants/form';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const baseUrl = `${location.protocol}//${location.host}`;

@inject('edcFormDesignerStore', 'edcSettingDesignerStore')
@observer
export default class Source extends React.Component {
    addFieldVal = React.createRef();

    constructor(props) {
        super();
        this.store = props.edcFormDesignerStore;
        this.settingStore = props.edcSettingDesignerStore;

        this.state = {
            isSaving: false,
            extendValue: '',
            languageId: '',
            url: '/edc/formview/',
            dlgVisible: false,
            dlgUrl: '',
            editUrlIndex: '',
        };
    }

    willDelete = (datas) => {
        const { onFormLinksChange } = this.settingStore;

        confirm({
            title: getLabel(522047, '您是否要删除选中的访问地址'),
            onOk: () => {
                const formLinks = datas.map(data => ({ link: data.url }));

                onFormLinksChange(formLinks);
            },
        });
    }

    deleteLink = (url) => {
        const { onFormLinksChange, formLinks } = this.settingStore;
        const links = [];

        confirm({
            title: getLabel(522052, '您是否要删除该访问地址'),
            onOk: () => {
                formLinks.map((link) => {
                    if (this.formatUrl(link.link) !== this.formatUrl(url)) { links.push({ link: link.link }); }
                });

                onFormLinksChange(links);
            },
        });
    }

    showDlg = (url) => {
        const { changeAddFieldsUrl } = this.settingStore;

        changeAddFieldsUrl(url);
        this.setState({ dlgUrl: url, dlgVisible: true });
    }

    scrollToError = (errorComDOM) => {
        if (errorComDOM) {
            const offset = errorComDOM.offsetTop;

            this.scrollSmoothTo(offset);
        }
    }

    scrollSmoothTo(position) {
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (callback) {
                return setTimeout(callback, 17);
            };
        }
        const $Wrapper = document.querySelector('.wea-edc-fields .ant-table-body');
        let scrollTop = $Wrapper.scrollTop;
        let step = function () {
            // 距离目标滚动距离
            let distance = position - scrollTop;
            // 目标滚动位置
            scrollTop = scrollTop + distance / 5;
            if (Math.abs(distance) < 1) {
                $Wrapper.scrollTo(0, position);
            } else {
                $Wrapper.scrollTo(0, scrollTop);
                requestAnimationFrame(step);
            }
        };
        step();
    }

    onOk = () => {
        const { shortkey } = this.store;
        const { editUrlIndex, url } = this.state;
        const { addExtendLink, addFieldsUrl, formLinks } = this.settingStore;
        const ind = toJS(formLinks).findIndex(link => link.link === addFieldsUrl);
        const dlg = this.addFieldVal.current.wrappedInstance;
        const { errorId, errorInd } = this.validateFieldData();

        if (errorId && dlg[errorId]) {
            const errorCom = document.querySelectorAll('.wea-edc-fields .wea-table-editable tbody tr')[errorInd];
            
            dlg[errorId].showError();
            this.scrollToError(errorCom);

        } else if (ind >= 0 && editUrlIndex !== ind) {
                message.warning(getLabel(522053, '已存在相同的url'));
            } else if (addFieldsUrl === `${url}${shortkey}`) {
                message.warning('请添加字段值');
            } else {
                addExtendLink({ link: addFieldsUrl }, editUrlIndex);
                this.setState({ dlgVisible: false });
            }
    }

    onCancel = () => {
        this.setState({ dlgVisible: false });
    }

    validateFieldData = () => {
        const { componentStore } = this.store;
        const { components } = componentStore;
        const dlg = this.addFieldVal.current.wrappedInstance;
        const fields = dlg.state.fields;
        let errorId = '';
        let errorInd = '';

        fields.some((field, index) => {
            const com = toJS(components).find(com => com.fieldName === field.fieldName);

            if (com && com.type === comsType.EMAIL) {
                if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(field.value)) {
                    errorId = field.id;
                    errorInd = index;   

                    return true;
                }
            } else if (com && com.type === comsType.MOBILE) {
                if (!/^1\d{10}$/.test(field.value)) {
                    errorId = field.id;
                    errorInd = index;

                    return true;
                }
            }
        });

        return { errorId, errorInd };
    }

    willAdd = () => {
        const { url } = this.state;
        const { shortkey } = this.store;
        const dlgUrl = `${url}${shortkey}`;
        const { formLinks } = this.settingStore;

        this.setState({ editUrlIndex: formLinks.length });
        this.showDlg(dlgUrl);
    };

    compileUrl = (record) => {
        const { url, id } = record;

        this.setState({ editUrlIndex: id });
        this.showDlg(url);
    }

    openPage = (url) => {
        window.open(url, '_blank');
    }

    formatUrl = (url) => { // 导入导出url支持当前页面域名，兼容之前带域名的老数据
        return '/edc/formview/' + url.split('/edc/formview/')[1];
    }

    render() {
        const { componentStore } = this.store;
        const { formLinks } = this.settingStore;
        const { dlgVisible, dlgUrl } = this.state;
        const { components } = componentStore;
        const buttons = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pkhw3h@onOk`} type="primary" onClick={this.onOk} >{getLabel('826', '确定')}</Button>,
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zj6ule@onCancel`} type="ghost" onClick={this.onCancel}>{getLabel('31129', '取消')}</Button>,
        ];
        const tableDatas = formLinks.map((link, index) => {
            const url = this.formatUrl(link.link);

            return { url, qrcode: url, id: index };
        });

        return (
            <div className="es-source">
                <div className="es-source-explain">
                    {getLabel(522063, '说明')}：<br />
                    {getLabel(522064, '1、跟踪数据来源支持通过设置表单多字段组合的方式来生成链接和二维码；')}<br />
                    {getLabel(522065, '2、通过链接设置的字段值会在表单填报时赋值给对应的表单字段；')}<br />
                    {getLabel(522066, '3、扩展字段可用表单的隐藏域进行替换，比如要收集2个子公司的数据并区分开来，可以设置一个隐藏域，设置隐藏域的值进行区分，生成2个表单链接或二维码进行发布；')}<br />
                    {getLabel(522067, '4、可设置外发填报使用的语言（【后端应用中心】-【语言中心】-【语言管理】中启用的语言），该设置只针对非内部用户生效，内部用户会根据用户的系统语言设置生效。')}<br />
                </div>
                <div className="link-setting-content">
                    <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@2b4tka`}
                      title=""
                      columns={[
                            {
                                title: getLabel(522054, '访问地址'),
                                dataIndex: 'url',
                                com: [{
                                    type: 'CUSTOM',
                                    key: 'url',
                                    render: text => (
                                        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@cs0wci@`} value={`${baseUrl}${text}`} viewAttr='1' />
                                    ),
                                }],
                            }, {
                                title: getLabel(522055, '二维码'),
                                dataIndex: 'qrcode',
                                className: 'center',
                                width: '60px',
                                com: [{
                                    type: 'CUSTOM',
                                    key: 'qrcode',
                                    render: text => (
                                        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@hafqn7@`} trigger={['hover']} placement="bottom" content={<WeaQrcode ecId={`${this && this.props && this.props.ecId || ''}_WeaQrcode@n7kpo1@`} text={`${baseUrl}${text}`} size={148} level="L" />}>
                                            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@05hole@`} type="qrcode" />
                                        </Popover>
                                    ),
                                }],
                            }, {
                                title: getLabel(522062, '操作'),
                                width: '150px',
                                className: 'center',
                                com: [{
                                    type: 'CUSTOM',
                                    render: (text, record) => (<span className="operations">
                                            <CopyToClipboard ecId={`${this && this.props && this.props.ecId || ''}_CopyToClipboard@neujrn@`} text={`${baseUrl}${record.url}`}
                                              onCopy={() => message.success(getLabel('502640', '复制URL成功'))}
                                            >
                                                <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@1i0s8u@`} placement="top" title={getLabel('502548', '复制网址')}>
                                                    <span><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@6ppe62@`} type="copy" /></span>
                                                </Tooltip>
                                            </CopyToClipboard>
                                            <span className="ant-divider" />
                                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@u2dayt@`} placement="top" title={getLabel('502549', '直接打开')}>
                                                <span><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@0p7gvb@`} type="desktop" onClick={() => this.openPage(`${baseUrl}${record.url}`)} /></span>
                                            </Tooltip>
                                            <span className="ant-divider" />
                                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@bnynnh@`} placement="top" title={getLabel('501169', '编辑')}>
                                                <span><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@omc7gn@`} type="edit" onClick={() => this.compileUrl(record)} /></span>
                                            </Tooltip>
                                            <span className="ant-divider" />
                                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@5lpwde@`} placement="top" title={getLabel('502286', '删除')}>
                                                <span><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@w4sgg2@`} type="delete" onClick={() => this.deleteLink(record.url)} /></span>
                                            </Tooltip>
                                        </span>),
                                }],
                            },
                        ]}
                      datas={tableDatas}
                      willAdd={this.willAdd}
                      showCopy={false}
                      willDelete={this.willDelete}
                      tableProps={{ scroll: { y: true } }}
                    />
                </div>

                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ufh66g`}
                  icon={'icon-coms02-Data-center'}
                  iconBgcolor="#1a57a0"
                  visible={dlgVisible}
                  title={getLabel(522056, '添加字段值')}
                  style={{ width: 580, height: 450 }}
                  buttons={buttons}
                  onCancel={this.onCancel}
                >
                    <AddFieldVal ecId={`${this && this.props && this.props.ecId || ''}_AddFieldVal@swic45`} visible={dlgVisible} coms={components} url={dlgUrl} ref={this.addFieldVal} />
                </WeaDialog>
            </div>
        );
    }
}
